package com.qf.dao;

import com.qf.pojo.Goods;
import com.qf.utils.ApacheUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.dao
 * @Description:
 * @Date 2022/5/24 21:48
 */
public class GoodsDaoImpl implements GoodsDao {
    private QueryRunner qr = new QueryRunner(ApacheUtil.getDataSource());
    @Override
    public int insertGoods(Goods goods) {
        String sql = "INSERT into tb_goods(name, pubdate, picture, price, star, intro, tid) value(?, ?, ? ,? ,?, ?, ?)";
        int count = 0;
        try {
            count = qr.update(sql, goods.getName(), goods.getPubdate(), goods.getPicture(),
                    goods.getPrice(), goods.getStar(), goods.getIntro(), goods.getTid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public List<Goods> findGoodsAll() {
        String sql = "select a.*, b.name typeName from tb_goods a " +
                        " left join tb_goods_type b on a.tid = b.id";
        List<Goods> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<Goods>(Goods.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Goods findGoodsById(Integer id) {
        String sql = "select * from tb_goods where id =?";
        Goods goods = null;
        try {
            goods = qr.query(sql, new BeanHandler<Goods>(Goods.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return goods;
    }
}
